package com.xxgc.demo.controller.error;

import cn.hutool.extra.mail.MailUtil;
import cn.hutool.jwt.JWTException;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.xxgc.demo.controller.aop.DataSourceMangerAOP;
import com.xxgc.demo.controller.error.myerror.IdCardDateException;
import com.xxgc.demo.controller.error.myerror.UserPhoneAlreadyExistsException;
import com.xxgc.demo.controller.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: SJY
 * @Date :2023/9/8 - 09 - 08 - 9:56
 * 全局异常拦截
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    //参数校验的拦截
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<Result> handleValidatedException(Exception e) {
        Result<List<String>> result = null;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<String> errorMessages = ex.getBindingResult().getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex = (ConstraintViolationException) e;
            List<String> errorMessages = ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<String> errorMessages = ex.getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        }
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    //参数转换异常，参数类型不匹配
    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    public ResponseEntity<Result> httpMessageNotReadableException(Exception e) {
        return new ResponseEntity<>(Result.error().msg("类型转换错误").errorMsg(e.getMessage()), HttpStatus.BAD_REQUEST);
    }

    //身份证时间日期异常
    @ExceptionHandler(value = {IdCardDateException.class})
    public ResponseEntity<Result> idCardDateException(IdCardDateException e) {
        return new ResponseEntity<>(Result.error().code(400).data(new String[]{e.getMessage()}), HttpStatus.BAD_REQUEST);
    }

    //无效JWT进行拦截
    @ExceptionHandler(value = {JWTException.class})
    public ResponseEntity<Result> jWTException(JWTException e) {
        log.warn("认证失败，Token无效");
        return new ResponseEntity<>(Result.error().code(401).msg("认证失败，Token无效"), HttpStatus.UNAUTHORIZED);
    }

    //手机号已存在异常
    @ExceptionHandler(value = {UserPhoneAlreadyExistsException.class})
    public ResponseEntity<Result> userPhoneAlreadyExistsException(UserPhoneAlreadyExistsException e) {
        return new ResponseEntity<>(Result.error().code(400).data(new String[]{"手机号已被注册"}), HttpStatus.BAD_REQUEST);
    }

    //数据库连接超时
    @ExceptionHandler(value = {SQLException.class})
    public ResponseEntity<Result> myException(SQLException e) {
        //通知开发或运维人员
        // sendMsgToDevOps("error","主数据库连接错误，连接失败，请及时修复",true,e);

        //切换数据源
        String source = DataSourceMangerAOP.getSource();

        source = "standby".equals(source) ? "master" : "standby";

        DataSourceMangerAOP.changeSource(source);

        return new ResponseEntity<>(Result.error().code(500).msg("系统异常"), HttpStatus.INTERNAL_SERVER_ERROR);
    }


    //-----------------------------------------告警发送平台--------------------------------------
    //开发人员信息
    @Value("${system.dev}")
    private String[] devInfo;
    //运维人员信息
    @Value("${system.ops}")
    private String[] opsInfo;
    @Value("${spring.profiles.active}")
    private String active;

    //通知运维和开发人员
    public void sendMsgToDevOps(String level,String message,boolean isSendAll,Exception e){
        //如果不是生产环境就不发信息
        if(!"prod".equals(active)){
            return;
        }


        String sysLevel = "提示";
        if("error".equals(level)){
            sysLevel = "严重";
        }else if("warn".equals(level)){
            sysLevel = "警告";
        }
        //所有异常默认运维都会收到一份
        for (String s : opsInfo) {
            //给用户的邮箱发送验证码
            MailUtil.send(s, "系统告警("+sysLevel+")", LocalDateTime.now()+"<br>"+message, false);
        }
        //如果是所有都收到就加上开发
        if(isSendAll){
            for (String s : devInfo) {
                MailUtil.send(s, "系统告警("+sysLevel+")", LocalDateTime.now()+"<br>"+message+"<br>"+e.getMessage(), false);
            }
        }

    }


}
